package com.liaoyin.travel.api.moble.attendance;

import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.view.ApiExternal.ApiExternalAttendance;
import com.liaoyin.travel.view.mine.attendance.AttendanceStatisticsDetailedView;
import com.liaoyin.travel.view.mine.attendance.AttendanceStatisticsView;
import com.liaoyin.travel.vo.attendance.AttendanceSettingVO;
import com.liaoyin.travel.base.api.JsonRestResponse;
import com.liaoyin.travel.base.api.RestUtil;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.UsersMapper;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.attendance.AttendanceSettings;
import com.liaoyin.travel.entity.attendance.PunchInRecord;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.attendance.AttendanceSettingsService;
import com.liaoyin.travel.service.attendance.AttendanceStatisticsService;
import com.liaoyin.travel.service.attendance.PunchInRecordService;
import com.liaoyin.travel.service.external.ApiExternalService;
import com.liaoyin.travel.service.team.TeamWorkerService;
import com.liaoyin.travel.util.DateUtil;
import com.liaoyin.travel.util.PartyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Api(tags={"考勤打卡(原来)"})
@RequestMapping("/moble/attendanceMoble")
public class AttendanceController {

   @Autowired
   private AttendanceSettingsService attendanceSettingsService;
   @Autowired
   private PunchInRecordService punchInRecordService;
   @Autowired
   private AttendanceStatisticsService attendanceStatisticsService;
   @Autowired
   private TeamWorkerService teamWorkerService;
   @Autowired
   private ApiExternalService apiExternalService;
    @Resource
    private UsersMapper usersMapper;

    @GetMapping("/selectAttendanceSettingsListOnMoble")
    @ResponseBody
    @ApiOperation(value = "前端查询考勤设置", notes = "前端查询考勤设置",response=AttendanceSettings.class,responseContainer="List")
    public JsonRestResponse selectAttendanceSettingsListOnMoble(){
    	
        return RestUtil.createResponse(this.attendanceSettingsService.selectAttendanceSettingsListOnMoble(null));
    }

    @GetMapping("/judgeCheckInIsAllowed")
    @ResponseBody
    @ApiOperation(value = "判断当前员工是否在允许的签到时间及范围", notes = "判断当前员工是否在允许的签到时间及范围",response=Map.class,responseContainer="Map")
    public JsonRestResponse judgeCheckInIsAllowed(
    		 @ApiParam(value = "经度", required = true) @RequestParam(required = true) String lat,
             @ApiParam(value = "纬度", required = true) @RequestParam(required = true) String log,
             @ApiParam(value = "打卡班次", required = true) @RequestParam(required = true) String checkShifts
    		){
    	
        return RestUtil.createResponse(this.punchInRecordService.judgeCheckInIsAllowed(lat, log, checkShifts,null));
    }

    
    @PostMapping("/insertPunchInRecord")
    @ResponseBody
    @ApiOperation(value = "前端打卡", notes = "前端打卡",response=Void.class)
    public JsonRestResponse insertPunchInRecord(
    		@RequestBody PunchInRecord punchInRecord){
    	this.punchInRecordService.insertPunchInRecord(punchInRecord);
        return RestUtil.createResponse();
    }

    @PostMapping("/getCurrentAttendanceSetting")
    @ResponseBody
    @ApiOperation(value = "获取当前需要打卡的打卡设置信息", notes = "获取当前需要打卡的打卡设置信息",response= AttendanceSettingVO.class)
    public JsonRestResponse getCurrentAttendanceSetting(){
        return RestUtil.createResponse(this.attendanceSettingsService.getCurrentAttendanceSetting());
    }
    
    
    @GetMapping("/selectPunchInRecordList")
    @ResponseBody
    @ApiOperation(value = "我的打卡记录", notes = "我的打卡记录",response=PunchInRecord.class,responseContainer="List")
    public JsonRestResponse selectPunchInRecordList(
    		@ApiParam(value = "日期【空：默认为今天】") @RequestParam(required = false) String checkTime,
    		@ApiParam(value = "用户id【可为空】") @RequestParam(required = false) String userId){
    	
        return RestUtil.createResponse(this.punchInRecordService.selectPunchInRecordListOnMoble(checkTime,userId));
    }
    
    @GetMapping("/selectAttendanceStatisticsMap")
    @ResponseBody
    @ApiOperation(value = "考勤统计", notes = "我的考勤统计",response=AttendanceStatisticsView.class,responseContainer="List")
    public JsonRestResponse selectAttendanceStatisticsMap(
    		@ApiParam(value = "结束日期", required = true) @RequestParam String checkendTime,
    		@ApiParam(value = "开始日期", required = true) @RequestParam String checkStartTime,
    		@ApiParam(value = "用户id【可为空】") @RequestParam(required = false) String userId){
        return RestUtil.createResponse(this.attendanceStatisticsService.selectAttendanceStatisticsMap(checkendTime, checkStartTime,userId));
    }
    
    
    @GetMapping("/selectAttendanceStatisticsDetailedList")
    @ResponseBody
    @ApiOperation(value = "考勤统计明细", notes = "我的考勤统计明细",response=AttendanceStatisticsDetailedView.class,responseContainer="List")
    public JsonRestResponse selectAttendanceStatisticsDetailedList(
    		@ApiParam(value = "当前页", required = true) @RequestParam(required = true) Integer num,
            @ApiParam(value = "每页条数", required = true) @RequestParam(required = true) Integer size,
    		@ApiParam(value = "结束日期", required = true) @RequestParam(required = true) String checkendTime,
    		@ApiParam(value = "开始日期", required = true) @RequestParam(required = true) String checkStartTime,
    		@ApiParam(value = "类型【1：出勤 2：休息 3：迟到 4：缺卡 5：旷工】", required = false) @RequestParam(required = false) String workType,
    		@ApiParam(value = "用户id【可为空】", required = false) @RequestParam(required = false) String userId){
        
    	return RestUtil.createResponse(new PageInfo<>(this.attendanceStatisticsService.selectAttendanceStatisticsDetailedList(num, size, checkendTime, checkStartTime, workType,userId)));
    }


    @GetMapping("/selectAttendanceStatisticsDetailedListByTime")
    @ResponseBody
    @ApiOperation(value = "部门员工考勤统计明细", notes = "部门员工考勤统计明细",response=AttendanceStatisticsDetailedView.class,responseContainer="Map")
    public JsonRestResponse selectAttendanceStatisticsDetailedListByTime(
            @ApiParam(value = "查询时间 yyyy-MM-dd", required = true) @RequestParam String  time
    ){
        Map<String, Object> map = this.attendanceStatisticsService.selectAttendanceStatistcsByTeamTime(time);
        return RestUtil.createResponse(map);
    }

    @GetMapping("/selectAttendanceStatisticsDetailedListByToday")
    @ResponseBody
    @ApiOperation(value = "今日部门员工考勤率及考勤统计明细", notes = "今日部门员工考勤率及考勤统计明细",response=ApiExternalAttendance.class,responseContainer="Map")
    public JsonRestResponse selectAttendanceStatisticsDetailedListByToday(){
        List<AttendanceStatisticsDetailedView> statisticsDetailedViews = this.attendanceStatisticsService.selectAttendanceStatisticsDetailedListByTime(DateUtil.getCurrentyyyymmdd());
        UserInfo userInfo = PartyUtil.getCurrentUserInfo();
        if(userInfo == null) {
        	throw new BusinessException("not.login");
        }
        List<UserTeam> usertramList = userInfo.getUserTeamList();
        if(usertramList==null || usertramList.size() == 0) {
        	throw new BusinessException("team.is.null");
        }
        StringBuffer teamId = new StringBuffer();
        for(UserTeam u:usertramList) {
        	teamId.append(u.getTeamId()+",");
        }
        List<Users> users = teamWorkerService.selectUsersListByTeamId(teamId.toString());
        List<AttendanceStatisticsDetailedView> tempList = new ArrayList<>();
        List<AttendanceStatisticsDetailedView> list = new ArrayList<>();
        List<AttendanceStatisticsDetailedView> notAttendings = new ArrayList<>();
        for (AttendanceStatisticsDetailedView view : statisticsDetailedViews) {
            if (Integer.valueOf(view.getWorkType()) == 3 || Integer.valueOf(view.getWorkType()) == 1 || Integer.valueOf(view.getWorkType()) == 4){
                tempList.add(view);
            }
            if (Integer.valueOf(view.getWorkType()) == 3 || Integer.valueOf(view.getWorkType()) == 4 || Integer.valueOf(view.getWorkType()) == 5){
                list.add(view);
            }
            if(Integer.valueOf(view.getWorkType()) == 5 || Integer.valueOf(view.getWorkType()) == 2){
                notAttendings.add(view);
            }
        }
        List<PunchInRecord> punchInRecords = this.punchInRecordService.selectTeamPunchInRecordListOnMoble(null);
        List<PunchInRecord> punchInRecords1 = this.punchInRecordService.selectTeamPunchInRecordList(null);
        int attending = 0;
        ArrayList<ApiExternalAttendance> views = new ArrayList<>();
        for (AttendanceStatisticsDetailedView detailedView : statisticsDetailedViews) {
            ApiExternalAttendance view = new ApiExternalAttendance();
            view.setUsersNickName(detailedView.getUsersNickName());
            view.setCheckTime(detailedView.getCheckTime() != null ? detailedView.getCheckTime().getTime():-1);
            view.setDetailedTime(detailedView.getDetailedTime().getTime());
            view.setWorkType(detailedView.getWorkType());
            views.add(view);
        }
        for (PunchInRecord record : punchInRecords) {
            record.setUserNikeName(this.usersMapper.selectByPrimaryKey(record.getUserId()).getNickName());
        }
        Float percentage = ((float)punchInRecords1.size()/(float) users.size())*100;

        Map map = new HashMap<>();
        map.put("percentage",percentage);
        map.put("notAttending", users.size()-punchInRecords1.size());
        map.put("attending",punchInRecords1.size());
        map.put("list",punchInRecords);
        tempList=null;
        users=null;
        statisticsDetailedViews=null;
        return RestUtil.createResponse(map);
    }

}
